from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from models.storage import Warehouse, Storage, Transport
from extensions import db
from datetime import datetime

storage_bp = Blueprint('storage', __name__)

# 仓库管理
@storage_bp.route('/warehouses')
@login_required
def warehouse_list():
    # 获取查询参数
    name = request.args.get('name', '')
    location = request.args.get('location', '')
    status = request.args.get('status', '')
    
    # 构建查询
    query = Warehouse.query
    if name:
        query = query.filter(Warehouse.name.like(f'%{name}%'))
    if location:
        query = query.filter(Warehouse.location.like(f'%{location}%'))
    if status:
        query = query.filter(Warehouse.status == status)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Warehouse.id.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('storage/warehouse_list.html',
                         warehouses=pagination.items,
                         pagination=pagination,
                         name=name,
                         location=location,
                         status=status)

@storage_bp.route('/warehouses/add', methods=['GET', 'POST'])
@login_required
def warehouse_add():
    if request.method == 'POST':
        warehouse = Warehouse(
            name=request.form.get('name'),
            location=request.form.get('location'),
            capacity=request.form.get('capacity'),
            temperature=request.form.get('temperature'),
            humidity=request.form.get('humidity'),
            notes=request.form.get('notes')
        )
        db.session.add(warehouse)
        db.session.commit()
        flash('仓库添加成功', 'success')
        return redirect(url_for('storage.warehouse_list'))
    return render_template('storage/warehouse_add.html')

@storage_bp.route('/warehouses/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def warehouse_edit(id):
    warehouse = Warehouse.query.get_or_404(id)
    if request.method == 'POST':
        warehouse.name = request.form.get('name')
        warehouse.location = request.form.get('location')
        warehouse.capacity = request.form.get('capacity')
        warehouse.temperature = request.form.get('temperature')
        warehouse.humidity = request.form.get('humidity')
        warehouse.status = request.form.get('status')
        warehouse.notes = request.form.get('notes')
        
        db.session.commit()
        flash('仓库信息更新成功', 'success')
        return redirect(url_for('storage.warehouse_list'))
        
    return render_template('storage/warehouse_edit.html', warehouse=warehouse)

@storage_bp.route('/warehouses/delete/<int:id>')
@login_required
def warehouse_delete(id):
    warehouse = Warehouse.query.get_or_404(id)
    db.session.delete(warehouse)
    db.session.commit()
    flash('仓库删除成功', 'success')
    return redirect(url_for('storage.warehouse_list'))

# 样本存储管理
@storage_bp.route('/storages')
@login_required
def storage_list():
    # 获取查询参数
    sample_code = request.args.get('sample_code', '')
    sample_type = request.args.get('sample_type', '')
    status = request.args.get('status', '')
    warehouse_id = request.args.get('warehouse_id', '')
    
    # 构建查询
    query = Storage.query
    if sample_code:
        query = query.filter(Storage.sample_code.like(f'%{sample_code}%'))
    if sample_type:
        query = query.filter(Storage.sample_type == sample_type)
    if status:
        query = query.filter(Storage.status == status)
    if warehouse_id:
        query = query.filter(Storage.warehouse_id == warehouse_id)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Storage.entry_time.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    # 获取仓库列表供筛选使用
    warehouses = Warehouse.query.all()
    
    return render_template('storage/storage_list.html',
                         storages=pagination.items,
                         pagination=pagination,
                         warehouses=warehouses,
                         sample_code=sample_code,
                         sample_type=sample_type,
                         status=status,
                         warehouse_id=warehouse_id)

@storage_bp.route('/storages/add', methods=['GET', 'POST'])
@login_required
def storage_add():
    warehouses = Warehouse.query.all()
    if request.method == 'POST':
        storage = Storage(
            warehouse_id=request.form.get('warehouse_id'),
            sample_code=request.form.get('sample_code'),
            sample_type=request.form.get('sample_type'),
            quantity=request.form.get('quantity'),
            storage_location=request.form.get('storage_location'),
            temperature_requirement=request.form.get('temperature_requirement'),
            humidity_requirement=request.form.get('humidity_requirement'),
            operator_id=current_user.id
        )
        db.session.add(storage)
        db.session.commit()
        flash('样本入库成功', 'success')
        return redirect(url_for('storage.storage_list'))
    return render_template('storage/storage_add.html', warehouses=warehouses)

@storage_bp.route('/storages/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def storage_edit(id):
    storage = Storage.query.get_or_404(id)
    warehouses = Warehouse.query.filter_by(status='normal').all()
    
    if request.method == 'POST':
        storage.warehouse_id = request.form.get('warehouse_id')
        storage.sample_type = request.form.get('sample_type')
        storage.quantity = request.form.get('quantity')
        storage.storage_location = request.form.get('storage_location')
        storage.temperature_requirement = request.form.get('temperature_requirement')
        storage.humidity_requirement = request.form.get('humidity_requirement')
        storage.status = request.form.get('status')
        
        db.session.commit()
        flash('样本信息更新成功', 'success')
        return redirect(url_for('storage.storage_list'))
        
    return render_template('storage/storage_edit.html', storage=storage, warehouses=warehouses)

@storage_bp.route('/storages/delete/<int:id>')
@login_required
def storage_delete(id):
    storage = Storage.query.get_or_404(id)
    if storage.status == 'in_transit':
        flash('运输中的样本不能删除', 'error')
        return redirect(url_for('storage.storage_list'))
    
    db.session.delete(storage)
    db.session.commit()
    flash('样本记录删除成功', 'success')
    return redirect(url_for('storage.storage_list'))

# 运输管理
@storage_bp.route('/transports')
@login_required
def transport_list():
    # 获取查询参数
    vehicle_number = request.args.get('vehicle_number', '')
    driver_name = request.args.get('driver_name', '')
    status = request.args.get('status', '')
    start_date = request.args.get('start_date', '')
    
    # 构建查询
    query = Transport.query
    if vehicle_number:
        query = query.filter(Transport.vehicle_number.like(f'%{vehicle_number}%'))
    if driver_name:
        query = query.filter(Transport.driver_name.like(f'%{driver_name}%'))
    if status:
        query = query.filter(Transport.status == status)
    if start_date:
        query = query.filter(db.func.date(Transport.start_time) == start_date)
    
    # 分页
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(Transport.start_time.desc()).paginate(
        page=page, per_page=10, error_out=False)
    
    return render_template('storage/transport_list.html',
                         transports=pagination.items,
                         pagination=pagination,
                         vehicle_number=vehicle_number,
                         driver_name=driver_name,
                         status=status,
                         start_date=start_date)

@storage_bp.route('/transports/add', methods=['GET', 'POST'])
@login_required
def transport_add():
    storages = Storage.query.filter_by(status='stored').all()
    if request.method == 'POST':
        transport = Transport(
            storage_id=request.form.get('storage_id'),
            vehicle_number=request.form.get('vehicle_number'),
            driver_name=request.form.get('driver_name'),
            driver_phone=request.form.get('driver_phone'),
            start_location=request.form.get('start_location'),
            end_location=request.form.get('end_location'),
            start_time=datetime.strptime(request.form.get('start_time'), '%Y-%m-%dT%H:%M'),
            estimated_arrival_time=datetime.strptime(request.form.get('estimated_arrival_time'), '%Y-%m-%dT%H:%M'),
            notes=request.form.get('notes')
        )
        # 更新样本状态
        storage = Storage.query.get(transport.storage_id)
        storage.status = 'in_transit'
        
        db.session.add(transport)
        db.session.commit()
        flash('运输任务创建成功', 'success')
        return redirect(url_for('storage.transport_list'))
    return render_template('storage/transport_add.html', storages=storages)

@storage_bp.route('/transports/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def transport_edit(id):
    transport = Transport.query.get_or_404(id)
    if request.method == 'POST':
        transport.vehicle_number = request.form.get('vehicle_number')
        transport.driver_name = request.form.get('driver_name')
        transport.driver_phone = request.form.get('driver_phone')
        transport.start_location = request.form.get('start_location')
        transport.end_location = request.form.get('end_location')
        transport.start_time = datetime.strptime(request.form.get('start_time'), '%Y-%m-%dT%H:%M')
        transport.estimated_arrival_time = datetime.strptime(request.form.get('estimated_arrival_time'), '%Y-%m-%dT%H:%M')
        transport.status = request.form.get('status')
        
        # 处理可能为空的温度和湿度值
        current_temperature = request.form.get('current_temperature')
        current_humidity = request.form.get('current_humidity')
        
        transport.current_temperature = float(current_temperature) if current_temperature else None
        transport.current_humidity = float(current_humidity) if current_humidity else None
        
        transport.notes = request.form.get('notes')
        
        db.session.commit()
        flash('运输任务更新成功', 'success')
        return redirect(url_for('storage.transport_list'))
        
    return render_template('storage/transport_edit.html', transport=transport)

@storage_bp.route('/transports/delete/<int:id>')
@login_required
def transport_delete(id):
    transport = Transport.query.get_or_404(id)
    if transport.status == 'in_transit':
        flash('运输中的任务不能删除', 'error')
        return redirect(url_for('storage.transport_list'))
    
    # 更新相关样本状态
    storage = Storage.query.get(transport.storage_id)
    if storage:
        storage.status = 'stored'
    
    db.session.delete(transport)
    db.session.commit()
    flash('运输任务删除成功', 'success')
    return redirect(url_for('storage.transport_list')) 